accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
expire = 0
updir = ''
picnewname = ''
g_object_name_type = ''
now = timestamp = Date.parse(new Date()) / 1000; 

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = '/template/oss_auth';
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText;
    }
    else
    {
    	common.alert("上传错误，请更换浏览器.");
    }
};

function get_signature()
{
    //可以判断当前expire是否超过了当前时间,如果超过了当前时间,就重新取一下.3s 做为缓冲
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")");
        
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        updir = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
　　len = len || 32;
　　var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
　　var maxPos = chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
    　　pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
	//增加图片位置标识
	picnewname = updir + knup.postion + $('#uid').val() + random_string(5) + suffix;
}


function set_upload_param(up, filename, ret)
{
	
    if (ret == false)
    {
        ret = get_signature()
    }
    
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : picnewname,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });
   
    up.start();
}

var uploader = new plupload.Uploader({
	runtimes : 'html5,html4,flash,silverlight',
	browse_button : 'mainupload', 
    //multi_selection: false,
	container: document.getElementById('tpsc0'),//生成from input地址
	flash_swf_url : 'Moxie.swf',
	silverlight_xap_url : 'Moxie.xap',
    url : img_host,

    filters: {
    	mime_types : [ //只允许上传图片和zip文件
    	               { title : "Image files", extensions :  "*"}, //"jpg,png,gif"
    	             ],
        max_file_size : '10mb', //最大只能上传10mb的文件
        prevent_duplicates : true //不允许选取重复文件
    },

	init: {
		PostInit: function() { 
			//初始化,只用于控件加载第一次,如提示控件初始化
			//uploader.runtime == 'html5'
			$(".moxie-shim").attr('style','position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden;');
			set_upload_param(uploader, '', false);
			//console.log(uploader.runtime);
		},
		FilesAdded: function(up, files) {
			//每次图片加载都会触发
			if(files[0].type=='image/jpeg' || files[0].type=='image/png' || files[0].type=='image/bmp' || files[0].type=='image/gif'){
				set_upload_param(uploader, '', false);
			}else{
				//可能不同手机检测得不到文件后缀,需要手动检测
				var divs = files[0].name.split('.');
				var real_type = divs[divs.length-1].toLowerCase();
				if(real_type == 'jpg' || real_type == 'jpeg' || real_type == 'png' || real_type == 'gif' || real_type == 'bmp' || real_type.substring(0,5)=='image'){
					set_upload_param(uploader, '', false);
				}else{
					for(var onefile in uploader.files) {
						uploader.removeFile(uploader.files[onefile].id);
					}
					common.alert('文件上传格式错误'+real_type);
				}
			}
		},

		BeforeUpload: function(up, file) {
			//console.log			//点击上传时候触发
            set_upload_param(up, file.name, true);
            //设置file.name
            file.name = picnewname;
        },

		UploadProgress: function(up, file) {
			/*send('上传中'+file.percent+'%');*/
			//console.log('上传:'+file.percent+'%');
		},

		FileUploaded: function(up, file, info) {
            if (info.status == 200)
            {
            	//文件名包括目录,目录需要进行转义
            	knup.syn_pic(file.name.replace('/',':'),'add');
            	//隐藏图片
            	var setclass = file.name.replace('/','-').replace('.','-');
            	//showIMG参数：图片地址,图片class
            	$('.content'+knup.postion).append(knup.showIMG(host+'/'+file.name,setclass));
            } 
            else
            {
            	console.log(info.response+'上传失败');
            } 
            
            //@todo 每次进行knup.postion清零,否则导致无法点击第一个出现图片插入区域错误.knup.postion =0;
        	$(".moxie-shim").attr('style','position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden;');//防止每次js修改导致input无法点击
		},

		Error: function(up, err) {
			//@todo 每次进行knup.postion清零,否则导致无法点击第一个出现图片插入区域错误.knup.postion =0;
            if (err.code == -600) {
            	common.alert('您传的图片文件太大');
            }
            else if (err.code == -601) {
            	console.log('601');
            	common.alert('请您上传正确的图片格式');
            }
            else if (err.code == -602) {
            	common.alert('相同图片只能上传一次');
            }
            else 
            {
            	common.alert(err.response);
            }
		}
	}
});

function send(text){
	$.ajax({
		method:'post',
		data:{text:text},
        url: "http://kn.s1.natapp.cc/test/log/",
        dataType: "json",
        success: function(data){
       	
        }
   });	
}
uploader.init();
//left: 0px; width: 298px;

